# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 13:46:27 2024

@author: 59567
"""
import pandas as pd

from datetime import datetime

from pyecharts.charts import Tab, Line
from pyecharts import options as opts
from plot_base import multi_grid_line, multi_macro_bar_or_line, item_timeline_seasonal, xy_match_same_freq_plot

from data_source import get_data_by_meta
from data_process import to_daily, to_monthly_mean, TjdSingleData, gen_xy_same_freq, cal_tztd_index

from utils import load_yaml_file
# now = datetime.now().strftime("%Y-%m-%d")


def set_data_begin_time(df, meta):
    filter_date = max([meta[y_name][1] for y_name in df.columns])
    df = df[df.index > filter_date]
    return df


def plot_html(df_macro, meta):
    # 创建一个Tab对象，用于存储图表
    tab = Tab(page_title=meta['page_name'])
    # 获取图表控制参数
    plot_ctrl = meta['plot_control']
    # 遍历图表控制参数
    for tab_name, names in plot_ctrl.items():
        # 获取图表类型
        chart_type = names[0]
        # 获取图表数据列名
        names = names[1:]
        # 根据列名获取数据
        df = df_macro.loc[:,names]
        # 删除全为NaN的列
        df = df.dropna(how='all')
        # 保留两位小数
        df = df.round(2)
        # 设置数据开始时间
        df = set_data_begin_time(df, meta['meta'])
        
        # 如果图表类型包含timeline
        if 'timeline' in chart_type:
            # 获取图表类型和频率
            chart_type, freq = chart_type.split('_')
            
            # 如果频率为D，则将数据转换为日数据
            if freq == 'D':
                year_dic = {y_name:to_daily(df[y_name]) for y_name in df.columns}
            # 如果频率为M，则将数据转换为月均数据
            elif freq == 'M':
                year_dic = {y_name:to_monthly_mean(df[y_name]) for y_name in df.columns}
            
            # 调用item_timeline_seasonal函数，生成图表
            b = item_timeline_seasonal(df, freq, year_dic)
        # 如果图表类型为bar或line
        elif chart_type in ['bar','line']:
            
            # 调用multi_macro_bar_or_line函数，生成图表
            b = multi_macro_bar_or_line(df, chart_type)
        # 如果图表类型为multi_line
        elif chart_type == 'multi_line':
            # 调用multi_grid_line函数，生成图表
            b = multi_grid_line(df)
        # 将图表添加到Tab对象中
        tab.add(b, tab_name)
    # 将Tab对象渲染为html文件
    tab.render(f"plot\{meta['save_name']}.html")


def iter_compare_macro_and_hf_data(df_macro, y_name, x_names):
        tab = Tab(page_title=f"{y_name}相关性分析")
        for x_name, x_process in x_names.items():
            df_xy = gen_xy_same_freq(df_macro, y_name, x_name, x_process)
            idx_fill, tztd_ratio = cal_tztd_index(df_xy)
            b = xy_match_same_freq_plot(df_xy, idx_fill, tztd_ratio)

            tab.add(b, x_name)
        tab.render(f"plot\{y_name}.html")


if __name__ == "__main__":
    # 读取配置信息，输出经济数据到plot文件夹里
    meta = load_yaml_file('config.yaml')
    df_macro = get_data_by_meta(meta['meta'])
    
    plot_html(df_macro, meta)
    compare_meta = load_yaml_file('compare.yaml')
    for y_name, x_names in compare_meta['hf_name'].items():
        x_names = compare_meta['hf_name'][y_name]
        iter_compare_macro_and_hf_data(df_macro, y_name, x_names)
